package com.mall.web.control.app.pay;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.mall.biz.mall.MallMarketingBizImpl;
import com.mall.biz.trade.impl.o2o.O2OTradeFactoryImpl;
import com.mall.client.commkey.CommKeyService;
import com.mall.client.item.ItemCategoryService;
import com.mall.client.item.MallItemService;
import com.mall.client.mall.MallService;
import com.mall.client.mallGroupBuy.MallGroupbBuyService;
import com.mall.client.order.MallItemOrderService;
import com.mall.client.trade.TradeService;
import com.mall.constant.TradeTypeConstant;
import com.mall.constant.TypeCommOnlyKeyConstant;
import com.mall.dto.TradePriceAndBuyCountDTO;
import com.mall.enums.RegionEnum;
import com.mall.pojo.Commkey;
import com.mall.pojo.ItemCategory;
import com.mall.pojo.Mall;
import com.mall.pojo.MallGroupBuy;
import com.mall.pojo.MallItem;
import com.mall.pojo.MallItemOrder;
import com.mall.pojo.MallMarketing;
import com.mall.pojo.Trade;
import com.mall.pojo.User;
import com.mall.query.MallMarketingQuery;
import com.mall.vo.item.MallItemVO;
import com.mall.web.annotation.UserSecurity;
import com.mall.web.control.app.result.MallResultController;
import com.mall.web.util.APPCookieUtil;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.MoneyUtil;
import com.mall.web.util.WebUtil;

@Controller
@RequestMapping("/order/")
public class OrderController {

	private static final Logger log = LoggerFactory.getLogger(OrderController.class);

	@Autowired
	private MallGroupbBuyService mallGroupBuyService;
	@Autowired
	private MallService mallService;
	@Autowired
	private TradeService tradeService;
	@Autowired
	private CommKeyService commKeyService;
	@Autowired
	private MallItemService mallItemService;
	@Autowired
	private MallItemOrderService mallItemOrderService;
	@Autowired
	private ItemCategoryService itemCategoryService;
	@Autowired
	private O2OTradeFactoryImpl o2oTradeFactoryImpl;
	@Autowired
	private MallMarketingBizImpl mallMarketingBiz;

	/**
	 * 店铺买单页面
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@UserSecurity
	@RequestMapping("orderMall")
	public String orderMall(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		modelMap.put("onlyKey", onlyKey);
		Long mallId = HttpUtil.getLongValueFromRequest(request, "mallId");
		Long itemId = HttpUtil.getLongValueFromRequest(request, "itemId");

		MallMarketingQuery query = new MallMarketingQuery();
		query.setMallId(mallId);
		query.setMallItemId(itemId);
		query.setOnlyKey(onlyKey);
		query.setType(0);
		MallMarketing mallMarketing = this.mallMarketingBiz.getMallMarketingByQuery(query);

		Mall mall = this.mallService.getMallById(mallId);
		modelMap.put("mall", mall);
		int app = APPCookieUtil.urlFromApp(request);
		modelMap.put("app", app);
		User user = WebUtil.getCurrentUser(request);
		modelMap.put("user", user);
		modelMap.put("mallMarketing", mallMarketing);
		return "order/orderMall";

	}

	/**
	 * 团购下单页面
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@UserSecurity
	@RequestMapping("orderGroupBuy")
	public String orderGroupBuy(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		User user = WebUtil.getCurrentUser(request);
		Long mallGroupBuyId = HttpUtil.getLongValueFromRequest(request, "mallGroupBuyId");
		MallGroupBuy mallGroupBuy = this.mallGroupBuyService.getMallGroupBuyById(mallGroupBuyId);
		if (mallGroupBuy == null) {
			log.error("代金卷错误");
		}
		Mall mall = this.mallService.getMallById(mallGroupBuy.getMallId());
		modelMap.put("mallGroupBuy", mallGroupBuy);
		modelMap.put("mall", mall);
		int app = APPCookieUtil.urlFromApp(request);
		modelMap.put("app", app);
		String referer = request.getHeader("Referer");
		modelMap.put("referer", referer);
		modelMap.put("user", user);
		return "order/orderGroupBuy";

	}

	/**
	 * O2O团购和买单去付款
	 * 
	 * @param type
	 * @param mallId
	 * @param itemCount
	 * @param mallGroupBuyId
	 * @param money
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */

	//@UserSecurity
	@RequestMapping("orderAction")
	@Transactional
	public String orderAction(@RequestParam(required = true) Integer type, @RequestParam(required = true) Long mallId,
			@RequestParam(required = false) Integer itemCount, @RequestParam(required = false) Long discountId,
			@RequestParam(required = false) Long parentId, HttpServletRequest request, HttpServletResponse response) {
		Double price = Double.parseDouble(request.getParameter("money"));
		Long money = MoneyUtil.getDBMoney(price);//乘以一百后的价格
		Trade trade = new Trade();
		trade.setMallId(mallId);
		// 公共属性的设置start
		commonSet(trade, request, response);
		// end
		trade.setTradeDiscountType(discountId);
		trade.setParentId(parentId);
		trade.setType(type);
		// 价格与份数start
		o2oTradeFactoryImpl.beforeInsert(request, trade);
		TradePriceAndBuyCountDTO tradePriceAndBuyCountDTO = o2oTradeFactoryImpl.pack4PirceAndBuyCount(request, type,
				money, itemCount, parentId);
		trade.setPrice(tradePriceAndBuyCountDTO.getPrice());
		trade.setBuyCount(tradePriceAndBuyCountDTO.getBuyCount());
		trade.setDiscountPrice(tradePriceAndBuyCountDTO.getDiscountPrice());
		// end

		int succ = this.tradeService.insertTrade(trade);
		if (succ > 0) {
			o2oTradeFactoryImpl.afterSuccInsert(request, trade);
			if (type==12) {
				return "redirect:/wxPay/auth.htm?orderId=" + trade.getId();
			}
			if(type == TradeTypeConstant.TYPE_BALANCEPAY){
				return "redirect:/eshop/pcPersonalCenter.htm";
			}
			return "redirect:/pay/pay.htm?orderId=" + trade.getId();
		} else {
			o2oTradeFactoryImpl.afterErrorInsert(request, trade);
			log.error("生成订单失败");
			return null; // TODO 跳转到error页
		}

	}

	/**
	 * 智慧餐厅下单
	 * 
	 * @param MallItemOrder
	 * @param request
	 * @param response
	 * @param modelMap
	 */
	@UserSecurity
	@RequestMapping("orderZhihuiAction")
	public String orderZhihuiAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		User user = WebUtil.getCurrentUser(request);
		Long tableNumId = HttpUtil.getLongValueFromRequest(request, "tableNumId");

		Long mallId = HttpUtil.getLongValueFromRequest(request, "mallId");
		Mall mall = this.mallService.getMallById(mallId);
		MallItemOrder mallItemOrder = new MallItemOrder();

		Long mallItemOrderId = HttpUtil.getLongValueFromRequest(request, "fireOrderId");
		if (mallItemOrderId != null) {
			mallItemOrder = mallItemOrderService.getMallItemOrderById(mallItemOrderId);
		}
		Integer mealNum = HttpUtil.getIntegerValueFromRequest(request, "mealNum");// 用餐人数
		String mallItemIds[] = request.getParameterValues("spId");// 菜品对应的id
		String nums[] = request.getParameterValues("spNum");// 菜品对应的数量
		long price = 0l;
		if (mallItemIds != null && nums != null && mallItemIds.length > 0 && nums.length > 0
				&& mallItemIds.length == nums.length) {
			List<MallItemVO> mallItemVOList = new ArrayList<>();
			MallItemVO mallItemVO = null;
			Integer itemCounts = 0;
			// long price = 0l;
			for (int i = 0; i < mallItemIds.length; i++) {
				Long mallItemId = Long.parseLong(mallItemIds[i]);
				Integer waimaiNo = Integer.parseInt(nums[i]);
				MallItem mallItem = mallItemService.getMallItemById(mallItemId);

				ItemCategory itemCategory = this.itemCategoryService.getItemCategoryById(mallItem.getItemCategoryId());

				mallItemVO = new MallItemVO();
				if (itemCategory == null) {
					mallItemVO.setCategoryName("其他");
				} else {
					mallItemVO.setCategoryName(itemCategory.getItemCategoryName());
				}

				mallItemVO.setMallItemId(mallItem.getId());
				mallItemVO.setNo(waimaiNo);
				mallItemVO.setMallItemTitle(mallItem.getTitleName());
				BigDecimal show = (new BigDecimal(mallItem.getPrice().longValue())).divide(new BigDecimal(100));
				mallItemVO.setPrice(show.doubleValue() + "");
				mallItemVO.setPic(mallItem.getMainPic());
				mallItemVOList.add(mallItemVO);
				itemCounts += waimaiNo;
				price = price + mallItem.getPrice() * waimaiNo;
			}
			String json = JSONArray.toJSONString(mallItemVOList);
			mallItemOrder.setBuyItemsJson(json);
			mallItemOrder.setBuyCount(itemCounts);
			mallItemOrder.setPrice(price);
		}

		mallItemOrder.setBuyUserId(user.getId());
		if (tableNumId == null) {
			mallItemOrder.setTableNumId(0l);
		} else {
			mallItemOrder.setTableNumId(tableNumId);
		}
		mallItemOrder.setMealNum(mealNum);
		mallItemOrder.setMallId(mallId);
		mallItemOrder.setStatus(0);
		mallItemOrder.setGmtCreate(new Date());
		mallItemOrder.setAttribute(tradeService.generateOrderNo());
		if (mallItemOrderId != null) {
			mallItemOrder.setGmtModify(new Date());
			this.mallItemOrderService.modifyMallItemOrder(mallItemOrder);
		} else {
			mallItemOrder.setGmtModify(new Date());
			this.mallItemOrderService.insertMallItemOrder(mallItemOrder);
		}

		Long orderId = mallItemOrder.getId();
		if (orderId == null || orderId == 0) {
			log.error("生成订单失败");
			return "redirect:/mallresult/error.htm";
		}

		String mallName = "";
		try {
			mallName = URLEncoder.encode(mall.getMallName(), MallResultController.UTF8);
		} catch (UnsupportedEncodingException e) {
		}
		return "redirect:/mallresult/success.htm?type=" + MallResultController.ZHIHUI_ORDER_TYPE + "&mallId=" + mallId
				+ "&operateId=" + mallItemOrder.getId() + "&mallName=" + mallName + "&price=" + price;

	}

	private void commonSet(Trade trade, HttpServletRequest request, HttpServletResponse response) {
		
		Integer payType = HttpUtil.getIntegerValueFromRequest(request, "payType");
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		User user = WebUtil.getCurrentUser(request);
		trade.setBuyUserId(user.getId());
		trade.setVersion(1);//下单初始版本值为1
		Long sellerId = null;
		if(onlyKey.intValue() == TypeCommOnlyKeyConstant.TYPE_MAIGEDIAN){//买个店暂且这么使用
			sellerId = 1l;
			String discountMess = HttpUtil.getStringValueFromRequest(request, "discountMess");
			trade.setDiscountMess(discountMess);
		}else{
			sellerId = mallService.getMallById(trade.getMallId()).getSellerId();
		}
		if (sellerId != null) {
			trade.setSellerId(sellerId);
		}

		trade.setOutTradeNo(tradeService.generateOrderNo());
		trade.setStatus(0);// 下单初始状态
		if(payType != null && payType >0){
			trade.setPayType(payType);// 下单初始支付方式
		}else{
			trade.setPayType(0);// 下单初始支付方式
		}
		trade.setGmtCreate(new Date());
		trade.setGmtModify(new Date());
		trade.setRefund(0);// 退款的初始值
		trade.setLogisticsId(0 + "");
		trade.setLogisticsStatus(0);
		List<Commkey> commKeyList = this.commKeyService.getComKeyByCommOnlyKey(onlyKey);
		trade.setCommOnlyKey(onlyKey);
		trade.setProvinceId(commKeyService.getRegionByList(RegionEnum.PROVINCE.getCode(), commKeyList));
		trade.setCityId(commKeyService.getRegionByList(RegionEnum.CITY.getCode(), commKeyList));
		trade.setAreaId(commKeyService.getRegionByList(RegionEnum.AREA.getCode(), commKeyList));
	}
	
	
	@RequestMapping("eshopBackOrderAction")
	@Transactional
	public String eshopBackOrderAction(@RequestParam(required = true) Integer type, @RequestParam(required = true) Long mallId,
			@RequestParam(required = false) Integer itemCount, @RequestParam(required = false) Long discountId,
			@RequestParam(required = false) Long parentId, HttpServletRequest request, HttpServletResponse response) {
		Double price = Double.parseDouble(request.getParameter("money"));
		Long money = (new BigDecimal(price)).multiply(new BigDecimal(100)).divide(new BigDecimal(1), 1, BigDecimal.ROUND_HALF_UP).longValue();
		Trade trade = new Trade();
		trade.setMallId(mallId);
		// 公共属性的设置start
		commonSet(trade, request, response);
		// end
		trade.setTradeDiscountType(discountId);
		trade.setParentId(parentId);
		trade.setType(type);
		// 价格与份数start
		o2oTradeFactoryImpl.beforeInsert(request, trade);
		TradePriceAndBuyCountDTO tradePriceAndBuyCountDTO = o2oTradeFactoryImpl.pack4PirceAndBuyCount(request, type,
				money, itemCount, parentId);
		trade.setPrice(tradePriceAndBuyCountDTO.getPrice());
		trade.setBuyCount(tradePriceAndBuyCountDTO.getBuyCount());
		trade.setDiscountPrice(tradePriceAndBuyCountDTO.getDiscountPrice());
		// end

		int succ = this.tradeService.insertTrade(trade);
		if (succ > 0) {
			boolean operateSucc = o2oTradeFactoryImpl.afterSuccInsert(request, trade);
			if(operateSucc){
				return "redirect:/eshop/backEshop/backTransferRecordList.htm?status=0";
			}
			throw new RuntimeException("增加余额失败！");
		} else {
			o2oTradeFactoryImpl.afterErrorInsert(request, trade);
			log.error("生成订单失败");
			return null; // TODO 跳转到error页
		}

	}
}
